import React, { useRef, useState } from 'react'
import { Form, Input, Button, Table, Select, Space, Modal, message } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import { formatDate } from '@/utils'
import { getUsersList, deleteUser } from '@/api/user'
import { IUserItem } from '@/types/user'
import CreateUser from './components/CreateUser'
import { ModelAction } from '@/types/modal'
import SearchForm from '@/components/SearchForm'
import { useAntdTable } from 'ahooks'
import AuthButton from '@/components/AuthButton'

const UserList: React.FC = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([])

  const [form] = Form.useForm()
  const createUserRef = useRef<{ open: (type: ModelAction, data?: IUserItem) => void }>()

  const getTableData = ({ current, pageSize }: { current: number; pageSize: number }, formData: IUserItem) => {
    return getUsersList({
      ...formData,
      pageNum: current,
      pageSize
    }).then(res => {
      console.log(res)

      return {
        total: res.data.page.total,
        list: res.data.list
      }
    })
  }
  const { tableProps, search } = useAntdTable(getTableData, { form, defaultPageSize: 5 })
  // 条件搜索
  const handleSearch = () => {
    search.submit()
  }

  // 重置
  const handleReset = () => {
    search.reset()
  }
  // 新增
  const handleCreateUser = () => {
    createUserRef.current?.open('create')
  }
  // 编辑
  const handleEdit = (record: IUserItem) => {
    createUserRef.current?.open('edit', record)
  }
  // 删除
  const handleDel = (userId: number) => {
    Modal.confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: <span>确定删除吗？</span>,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        handleDelUser([userId])
      }
    })
  }
  // 批量删除
  const handleBatchDelete = () => {
    Modal.confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: <span>确定删除吗？</span>,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        handleDelUser(selectedRowKeys)
      }
    })
  }

  const handleDelUser = (userIds: number[]) => {
    deleteUser(userIds).then(() => {
      message.success('删除成功')
      setSelectedRowKeys([])
      search.reset()
    })
  }
  const columns: ColumnsType<IUserItem> = [
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId'
    },
    {
      title: '用户名称',
      dataIndex: 'userName',
      key: 'userName'
    },
    {
      title: '用户邮箱',
      dataIndex: 'userEmail',
      key: 'userEmail'
    },
    {
      title: '用户角色',
      dataIndex: 'role',
      key: 'role',
      render(role: number) {
        return {
          0: '超级管理员',
          1: '管理员',
          2: '体验管理员',
          3: '普通用户'
        }[role]
      }
    },
    {
      title: '用户状态',
      dataIndex: 'state',
      key: 'state',
      render(state: number) {
        return {
          1: '在职',
          2: '离职',
          3: '试用期'
        }[state]
      }
    },
    {
      title: '注册时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render(createTime: string) {
        return formatDate(createTime)
      }
    },
    {
      title: '操作',
      key: 'address',
      render(record) {
        return (
          <Space>
            <AuthButton type='text' onClick={() => handleEdit(record)} auth='	user@edit'>
              编辑
            </AuthButton>
            <AuthButton type='text' danger onClick={() => handleDel(record.userId)} auth='user@delete'>
              删除
            </AuthButton>
          </Space>
        )
      }
    }
  ]
  return (
    <div className='list_page'>
      <div className='list_page__header'>
        <SearchForm form={form} initialValues={{ state: 1 }} onSubmit={handleSearch} onReset={handleReset}>
          <Form.Item label='用户ID' name='userId'>
            <Input />
          </Form.Item>
          <Form.Item label='用户名称' name='userName'>
            <Input />
          </Form.Item>
          <Form.Item name='state' label='状态'>
            <Select>
              <Select.Option value={0}>所有</Select.Option>
              <Select.Option value={1}>在职</Select.Option>
              <Select.Option value={2}>离职</Select.Option>
              <Select.Option value={3}>试用期</Select.Option>
            </Select>
          </Form.Item>
        </SearchForm>
      </div>
      <div className='list_page__wrapper'>
        <div className='list_page__wrapper__toolbar'>
          <div className='list_page__wrapper__toolbar__title'>用户列表</div>
          <div className='list_page__wrapper__toolbar__right'>
            <AuthButton type='primary' style={{ marginRight: 8 }} onClick={handleCreateUser} auth='user@create'>
              新增
            </AuthButton>
            <AuthButton type='primary' danger onClick={handleBatchDelete} auth='user@patchDelete'>
              批量删除
            </AuthButton>
          </div>
        </div>
        <div>
          <Table
            columns={columns}
            rowKey='userId'
            rowSelection={{
              type: 'checkbox',
              selectedRowKeys,
              onChange(selectedRowKeys) {
                setSelectedRowKeys(selectedRowKeys as number[])
              }
            }}
            {...tableProps}
            pagination={{
              ...tableProps.pagination,
              pageSizeOptions: [5, 10, 20, 50],
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: function (total) {
                return `总共：${total}条`
              }
            }}
          ></Table>
        </div>
      </div>
      <CreateUser
        mRef={createUserRef}
        update={() => {
          search.reset()
        }}
      />
    </div>
  )
}

export default UserList
